//
//  RequestParamaters.swift
//  ClockWidget
//
//  Created by TSYH on 2024/3/14.
//

import Alamofire

public class RequestParamaters {
    public static var apiHost: String = ""
    static var commonParameters: [String: Any] = [:]
    static var headers: [String: String] = [:]
    
    public static func appendCommon(_ value: Any, for key: String) {
        commonParameters[key] = value
    }
    
    public static func appendCommons(_ params: [String: Any]) {
        commonParameters.merge(params) { obj1, obj2 in
            return obj2
        }
    }
    
    public static func value(for key: String) -> Any? {
        return commonParameters[key]
    }
    
    public static func addHeader(_ value: String, for key: String) {
        headers[key] = value
    }
    
    public static func removeHeader(for key: String) {
        headers.removeValue(forKey: key)
    }
}

enum RequestSecurityType: Int {
    case RequestSecurityType_Anonym = 0
    case RequestSecurityType_RegisteredDevice = 0x0003
    case RequestSecurityType_User = 0x0007
}

extension Parameters {
    mutating func appendCommonParameters() {
        append(RequestParamaters.commonParameters)
    }
    
    mutating func append(method: String, 
                         parameters: [String: Any]) {
        // self["_mt"] = method
        append(parameters)
    }
    
    mutating func append(_ parameters: [String: Any]) {
        for key in parameters.keys {
            let value = parameters[key];
            if let dictionaryValue = value as? Dictionary {
                if let data = try? JSONSerialization.data(withJSONObject: dictionaryValue, options: .init()) {
                    if let JSONString = String(bytes: data, encoding: .utf8) {
                        self[key] = JSONString
                    }
                }
            } else if let arrayValue = value as? Array<Any> {
                if let data = try? JSONSerialization.data(withJSONObject: arrayValue, options: .init()) {
                    if let JSONString = String(bytes: data, encoding: .utf8) {
                        self[key] = JSONString
                    }
                }
            } else {
                self[key] = value;
            }
        }
    }
}
